package com.zjsru.leetcode75.level1;

/**
 * @Author: cookLee
 * @Date: 2023-10-04
 * 压缩字符串
 */
public class Compress {

    /**
     * 主
     * 输入：chars = ["a","a","b","b","c","c","c"]
     * 输出：返回 6 ，输入数组的前 6 个字符应该是：["a","2","b","2","c","3"]
     * 解释："aa" 被 "a2" 替代。"bb" 被 "b2" 替代。"ccc" 被 "c3" 替代。
     * \
     * 输入：chars = ["a"]
     * 输出：返回 1 ，输入数组的前 1 个字符应该是：["a"]
     * 解释：唯一的组是“a”，它保持未压缩，因为它是一个字符。
     * \
     * 输入：chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
     * 输出：返回 4 ，输入数组的前 4 个字符应该是：["a","b","1","2"]。
     * 解释：由于字符 "a" 不重复，所以不会被压缩。"bbbbbbbbbbbb" 被 “b12” 替代。
     * @param args args
     */
    public static void main(String[] args) {
        Compress compress = new Compress();
        char[] chars = new char[]{'a','a','b','b','c','c','c'};
        System.out.println(compress.compress(chars));
    }

    /**
     * 压缩:双指针
     *
     * @param chars 字符
     * @return int
     */
    public int compress(char[] chars) {
        int len = chars.length;
        int write = 0, left = 0;
        for (int read = 0; read < len; read++) {
            if (read == len - 1 || chars[read] != chars[read + 1]) {
                //获取要改写的位置
                chars[write++] = chars[read];
                int num = read - left + 1;
                //将位数循环改成数字
                if (num > 1) {
                    int anchor = write;
                    while (num > 0) {
                        chars[write++] = (char) (num % 10 + '0');
                        num /= 10;
                    }
                    this.reserve(chars, anchor, write - 1);
                }
                left = read + 1;
            }
        }
        return write;
    }

    /**
     * 反转：通过除法获得的数字存在相反的情况
     *
     * @param chars 字符
     * @param left  左
     * @param right 右侧
     */
    private void reserve(char[] chars, int left, int right) {
        while (left < right) {
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            left++;
            right--;
        }
    }
}
